<template>
    <u-popup :show="showPopup" @close="close"> 
        <view class="specsPop padding30" v-if="pageData">
            <view class="d-flex">
                <image class="img bor_radius_4 m-right20 f-shrink-0" :src="$imgUrls(currentSpecs.img || pageData.img)" mode="aspectFill"></image>
                <view class="d-flex f-column j-sb">
                    <view class="p-right40 size28">{{ pageData.name }}</view>
                    <view>
                        <text class="color_FOD size32 bold">￥</text>
                        <text class="color_FOD size40 bold">{{ currentSpecs.price || pageData.price }}</text>
                    </view>
                </view>
            </view>
            <view class="scroll-y" style="max-height: 50vh;" v-if="specsList.length">
                <view v-for="(item, index) in specsList" :key="index">
                    <view class="size28 color_33 bold m-top30 m-bot20">{{ item.title }}</view>
                    <view v-if="item.list">
                        <view class="specsItm d-inline-block color_66 bor_radius_30s" :class="{ active: specs_ids[index] == itm.specs_id, color_cc: !itm.state }" 
                            @click="handleSpecs(index, itm.state, itm.specs_id)" v-for="(itm, idx) in item.list" :key="idx">{{ itm.title }}</view>
                    </view>
                </view>
            </view>
            <view class="d-flex j-sb a-center">
                <view class="size28 color_33 bold m-top30 m-bot40">数量</view>
                <view><u-number-box v-model="v_input" integer :max="stock" @overlimit="overlimit"></u-number-box></view>
            </view>
            <view class="confirmBtn bgFF4B size30 white bold text-center" @click="handleSubmit">确定</view>
        </view>
    </u-popup>
</template>

<script>
    export default {
        props: {
            showPopup: {
                type: Boolean,
                default: false
            },
            pageData: {
                type: Object,
                default: () => ({})
            }
        },
        data() {
            return {
                specsList: [], // 规格列表
                specsCopy: '', // 原始数据字符串
                specs_ids: [],
                stock: '', // 当前规格组合的库存或总库存
                currentSpecs: '',
                v_input: 1 // 计数器
            }
        },
        watch: {
            pageData: {
                deep: true,
                handler(newVal) {
                    this.init()
                    if(!newVal) return
                    this.stock = newVal.stock
                    if(!newVal.getGoodsSpecs) return
                    let { specsList, specsPrice } = newVal.getGoodsSpecs
                    if (specsList && specsPrice) {
                        this.specsList = specsList
                        this.specsCopy = JSON.stringify(this.specsList)
                        let first = specsPrice.find(item => item.stock > 0) // 接口返回的specs_ids默认从小到大排序
                        if (first) {
                            specsList.forEach((item, index) => {
                                // 强制按照规格类别排序且个数一致
                                let obj = item.list.find(itm => first.specs_ids.includes(itm.specs_id))
                                this.specs_ids[index] = obj ? obj.specs_id : ''
                            })
                            this.stock = first.stock
                            this.currentSpecs = first
                        }
                    }
                }
            }
        },
        methods: {
            close() {
                this.$emit('close')
            },
            init() {
                this.specsList = []
                this.specs_ids = []
                this.currentSpecs = ''
                this.v_input = 1
            },
            overlimit(type) {
                if (type == 'plus') {
                    this.$Toast('库存不足')
                }
            },
            handleSpecs(index, itmState, id) {
                // 类别索引,规格状态,规格id
                if (!itmState) return // 禁选
                if (this.specs_ids[index] == id) return // 已选

                let { specsPrice } = this.pageData.getGoodsSpecs
                this.specs_ids[index] = id // 非响应式
                let empty = this.specs_ids.filter((item) => !item)

                if (!empty.length) {
                    // 已选完
                    let up = this.specs_ids.slice().sort((a, b) => a - b) // 创建副本再排序不影响原数组
                    let current = specsPrice.find((item) => item.specs_ids == up.toString())

                    if (current) {
                        this.specs_ids = [...this.specs_ids] // 更新视图
                        this.stock = current.stock
                        this.currentSpecs = current
                        // 当前所选类别有无禁选规格，无则还原list
                        let result = this.specsList[index].list.find((item) => !item.state)
                        if (!result) this.specsList = JSON.parse(this.specsCopy)
                    } else {
                        // 没找到为undefined
                        this.specs_ids = this.specs_ids.map((item) => (item == id ? id : '')) // 只保留当前所选规格，其余类别规格id清空
                    }
                } else if (empty.length == 1) {
                    // 仅剩一个类别未选，需判断该类别有无禁选规格
                    this.specs_ids = [...this.specs_ids]
                    // 未选类别索引
                    let i = this.specs_ids.findIndex((item) => !item)
                    this.specsList[i].list.forEach((item) => {
                        let arr = JSON.parse(JSON.stringify(this.specs_ids))
                        arr[i] = item.specs_id // 每一项规格组合
                        let result = specsPrice.find((itm) => itm.specs_ids == arr.sort((a, b) => a - b).toString())
                        item.state = result ? true : false
                    })
                } else {
                    this.specs_ids = [...this.specs_ids]
                }
            },
            handleSubmit() {
                if (this.specsList.length) {
                    let empty = this.specs_ids.findIndex((item) => !item)
                    if (empty > -1) return this.$Toast('请选择规格')
                }
                if (this.v_input > this.stock) return this.$Toast('库存不足')

                // 加入购物车
                this.$http.post({
                    url: '/zzj_singleSaleApi/joinCart',
                    data: {
                        num: this.v_input,
                        specs_bind_id: this.currentSpecs.id || '',
                        specs_bind_text: this.currentSpecs.specs_title || '',
                        goods_id: this.pageData.goods_id
                    }
                }).then((res) => {
                    if (res.errcode != 100) return this.$Toast(res.msg)
                    this.close()
                    this.$Toast('加入购物车成功')
                })
            }
        }
    }
</script>

<style lang="scss" scoped>
    .specsPop {
        .img {
            width: 168rpx;
            height: 168rpx;
        }

        .specsItm {
            background: #f4f4f4;
            border: 2rpx solid #f4f4f4;
            padding: 8rpx 36rpx;
            margin: 0 20rpx 20rpx 0;

            &.active {
                background: #fff0f0;
                border: 2rpx solid #ff4b4e;
                color: #ff4b4e;
            }
        }

        .confirmBtn {
            margin-bottom: constant(safe-area-inset-bottom);
            margin-bottom: env(safe-area-inset-bottom);
            width: 100%;
            line-height: 80rpx;
            border-radius: 80rpx;
        }

        .btn {
            margin-bottom: constant(safe-area-inset-bottom);
            margin-bottom: env(safe-area-inset-bottom);
            width: 48%;
            height: 72rpx;
            border-radius: 36rpx;
        }
    }
</style>